<template>
  <li style="margin-left: 0!important">
<!--    @contextmenu="rightClick($event)"-->
   <a href="javascript:void(0)"
      @contextmenu="rightClick($event)"
      style="font-family: 'Heiti SC';font-size: 14px;color: white;display: inline-block"
      :style="{marginLeft: item.name === '我创建的' && item.children ? '' : '8px',width:item.name === '我创建的' && item.children ? '200px' : '179px',
      borderRadius: item.name === '我创建的' && item.children ? '15px' : '',cursor: item.name === '我创建的' && item.children ? 'default' : 'pointer',}"
      :title="item.name">
       <span v-if="!item.leaf" @click="toggle(item)" style="display: inline-block">
<!--        <i :style="{display : item.id == 0 ? 'none' : '',marginLeft:'10px'}"-->
<!--          :class="['ele_id_null','ele_id_' + item.id,item.open ? item.loading-->
<!--                ? 'el-icon-loading'-->
<!--                : 'el-icon-caret-bottom'-->
<!--              : 'el-icon-caret-right']"></i>-->
<!--        <i :style="{display : item.id == 0 ? 'none' : '',marginLeft:'10px',color:'white'}"-->
<!--           :class="['ele_id_null','ele_id_' + item.id,item.open ? item.loading-->
<!--                ? 'el-icon-loading'-->
<!--                : 'el-icon-caret-right'-->
<!--              : 'el-icon-caret-right']"></i>-->
       <i :style="{display : item.id == 0 ? 'none' : '',marginLeft:'10px',color:'white',fontSize:'10px'}"
          :class="['ele_id_null','ele_id_' + item.id,item.open ? item.loading
                ? 'el-icon-loading'
                : 'fa fa-folder-o'
              : 'fa fa-folder-o']"></i>



<!--         {{item.id}}-->
<!--        <i v-if="clickId >= 0" :style="{color: clickId.toString() === item.id.toString()  ? '#fc9901' : '#444444'}"><span>{{ item.name }}</span></i>-->
<!--        <i v-if="clickId.toString() === item.id.toString()" style="color:#fc9901;"><span>{{ item.name }}</span></i>-->
<!--        <i v-else style="color:#444444;"><span>{{ item.name }}</span></i>-->

<!--         大标题-->
<!--         'ele_id_' + item.id-->
        <i :class="['ele_id_null']"
           style="font-family: 'Heiti SC';font-size: 14px;color: white;display: inline-block;background-color: #409eff;width: 200px!important;position: relative;" v-if="item.children">
          <span style="display: inline-block;width: 188px!important;margin-left: 12px;">{{ item.name }}</span>
<!--           @click="rightClick($event)"-->
<!--           @contextmenu="rightClick($event)"-->
          <i class="fa fa-plus-circle"
             @click="newCreateNewFolderFunc()"
             style="color: white;position: absolute;right: 10px;top:50%;transform: translate(0,-50%);font-size: 18px;cursor: pointer"></i>
        </i>

<!--         child-->
        <i :class="['ele_id_' + item.id,'ele_id_null']" style="font-family: 'Heiti SC';font-size: 14px;color: white" v-else><span
          style="display: inline-block;overflow-x: hidden;width: 154px;white-space: nowrap;text-overflow: ellipsis;float: right;margin-left: 3px">{{ item.name }}</span></i>

      </span>
      <span v-else-if="item.leaf" @click="checkRunning">
        <i class="fa fa-flask"></i>
        <i :style="itemStyle">{{ item.name }}</i>
      </span>
    </a>
    <ul v-show="item.open" v-if="!item.leaf">
      <ProjectTree
        v-for="childItem in item.children"
        :item="childItem"
        :parentItem="item"
        @getInfoList="getInfoList"
        :key="childItem.id"
      ></ProjectTree>
    </ul>
  </li>
</template>
<script>
import { project, getHasAuthProjectList } from "@/api/sourceDetail";
import { mapGetters } from "vuex";
export default {
  name: "ProjectTree",
  props: ["item", "parentItem", "isBeAuthorList"], //isBeAuthorList = true 即该数据为授权的工程列表
  data: function() {
    return {
      itemStyle: {
        color: ""
      },

      clickId: 0
    };
  },
  computed: {
    ...mapGetters(["httpServer"]),
    flowData: function() {
      return this.$store.state.project.flowData;
    },
    currentProjectItem: function() {
      return this.flowData.currentProjectItem;
    },
    username() {
      return this.$store.state.global.username;
    }
  },
  watch: {
    currentProjectItem: function(val) {
      this.changeStyle(val);
    }
  },
  created: function() {
    this.changeStyle(this.currentProjectItem);
  },
  methods: {
    getInfoList(val) {
      this.$emit("getInfoListVal", val);
    },
    toggle: function(e) {
      // console.log(JSON.parse(JSON.stringify(e)));
      if (e.id && e.id !== 0) {
        localStorage.setItem("clickToolsProjectId", e.id);
        // localStorage.setItem("clickToolsProjectName", e.name);
        this.resetSetItem("clickToolsProjectName", e.name);
        // this.$emit("getClickName", e.name);
      } else {
        this.resetSetItem("clickToolsProjectName", "");
      }

      // this.clickId = e.id.toString()
      // console.log(JSON.parse(JSON.stringify(e.id)));
      if (e.id !== 0) {
        let that = this;
        if (this.isBeAuthorList) {
          //查询授权的项目
          getHasAuthProjectList().then(res => {
            if (res.status === "SUCCESS") {
              // console.log("%c 🍐 res", "color:#ea7e5c", '已授权项目  >>>>>>>> ',JSON.parse(JSON.stringify(res)));
              res.data &&
                res.data.map(ele => {
                  ele["isBeAuthorProject"] = true;
                });
              this.$emit("getInfoListVal", res.data, that.isBeAuthorList);
            }
          });
        } else {
          project(e.id).then(res => {
            // console.log("%c 🍐 res", "color:#ea7e5c", JSON.parse(JSON.stringify(res)));
            this.$emit("getInfoList", res.data, that.isBeAuthorList);
          });
        }
      }

      // console.log(e.id);
      this.$emit("getClickId", e.id);

      //文件夹的展开关闭
      var that = this;
      if (!this.item.leaf) {
        this.item.open = !this.item.open;
        // this.item.open = true;
        if (this.item.children && this.item.children.length == 0) {
          //如果该节点已经存在children节点，则不再重复获取
          this.item.loading = true;
          this.flowData.currentParentItem = this.item;
          //获取添加子树
          this.$store.dispatch("getMenuProjectList", 3);
        }
      }
      // console.log(JSON.parse(JSON.stringify(this.flowData.currentParentItem)));

      this.item.open = true;

      let eleNull = document.querySelectorAll(".ele_id_null");
      let ele = document.querySelectorAll(".ele_id_" + e.id);
      // console.log(eleNull,ele);

      eleNull &&
        eleNull.forEach(val => {
          // val.style.color = "#444444";
          val.style.color = "#ffffff";
        });
      ele &&
        ele.forEach(item => {
          item.style.color = "#fc9901";
        });
    },
    changeStyle: function(val) {
      if (this.item.id == val.id) {
        this.itemStyle.color = "#e29012";
      } else {
        this.itemStyle.color = "";
      }
    },
    checkRunning: function() {
      // if (!this.flowData.isRunning) {
      //   this.editComponent();
      // } else {
      //   this.$notify({
      //     type: "warning",
      //     message: "工程运行中，请稍后再试！"
      //   });
      // }
    },
    editComponent: function() {
      //工程项点击事件
      if (this.flowData.projectChange) {
        this.$message({
          type: "warning",
          message: "操作频繁，数据准备中，请稍后再试！"
        });
      } else {
        //设置组件切换状态为true
        this.flowData.projectChange = true;
        //切换前对工程进行提交保存
        this.localStorageSave(true);
        this.flowData.propsContentHeight = this.$(
          ".drawingWork .eProperty"
        ).height();
        //设置当前项的目标父类集合
        console.log(this.parentItem);
        console.log(this.item);
        this.flowData.currentParentItem = this.parentItem;
        //设置当前选中文档树
        this.flowData.currentProjectItem = this.item;
        //设置当前操作工程信息
        this.flowData.currentProjectDetail = this.item.project;
        var localJSON = localStorage.getItem(
          this.username + "_" + this.item.project.id
        );
        if (localJSON) {
          this.flowData.projectChange = false;
          this.$confirm("检测到最后一次修改未提交, 是否从本地加载?", "提示", {
            confirmButtonText: "是",
            cancelButtonText: "否",
            type: "warning"
          })
            .then(() => {
              this.$srore.dispatch("fillCurrentJson", {
                json: localJSON
              });
            })
            .catch(() => {
              //从服务端获取工程流程数据并填充
              this.$store.dispatch("getCurrentFlowJson");
            });
        } else {
          //从服务端获取工程流程数据并填充
          this.$store.dispatch("getCurrentFlowJson");
        }
        this.$store.commit(
          "updateMenuProjectSelectComponent",
          "ProjectContentMsg"
        );
      }
    },
    rightClick: function(event) {
      // console.log(event);
      if (this.isBeAuthorList) {
        //isBeAuthorList = true 即该数据为授权的工程列表
        return;
      }
      //右键操作前加载子目录
      this.item.loading = true;
      this.flowData.currentParentItem = this.item;
      //获取添加子树
      this.$store.dispatch("getMenuProjectList", 3);
      //阻止默认菜单事件
      if (document.all) {
        window.event.returnValue = false;
      } else {
        event.preventDefault();
      }
      if (this.flowData.isRunning) {
        this.$notify({
          type: "warning",
          message: "工程运行中，请稍后再试！"
        });
        return;
      }
      this.localStorageSave(true); //右键时也要对工程提交保存
      this.flowData.rightContentTargetItem = this.item;
      this.flowData.rightContentTargetProject = this.item.project;
      //设置父类项
      this.flowData.currentParentItem = this.parentItem;
      //更新content_menu 坐标位置
      var dom = document.getElementsByClassName("mCom")[0]; //获取容器dom
      var centerDomOffset = dom.getBoundingClientRect();
      var contentHeight = 287; //file 196  root 118
      if (this.item.id == 0) {
        contentHeight = 118;
      } else if (!this.item.leaf) {
        contentHeight = 209;
      } else if (this.item.leaf) {
        contentHeight = 287;
      }
      this.flowData.projectContextMenuMsg = {
        left: event.clientX - centerDomOffset.left,

        top:
          event.clientY - centerDomOffset.top + contentHeight + 52 >
          centerDomOffset.bottom
            ? centerDomOffset.bottom - 52 - contentHeight > 0
              ? centerDomOffset.bottom - 52 - contentHeight
              : 0
            : event.clientY - centerDomOffset.top,
        display: "block"
      };
    },

    //创建新目录
    newCreateNewFolderFunc() {
      this.$store.state.project.flowData.projectContextMenuMsg.display = "none";
      this.$store.state.project.flowData.nodeRightContentMsg.display = "none";
      this.$store.state.project.flowData.contextMenuMsg.display = "none";
      this.$store.state.project.modelMenu.contentMenuMessage.display = "none";
      //如果当前项为文件夹时，设置当前项为父类项
      // this.$store.state.project.flowData.currentParentItem = this.$store.state.project.flowData.rightContentTargetItem;
      this.$store.state.project.flowData.currentParentItem = this.parentItem;
      var that = this;
      this.$prompt("请输入目录名称", "创建目录", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: "请输入目录名称",
        inputValidator(val) {
          var reg = /^(?! +$).+/;
          if (!reg.test(val) || val == null) {
            return "名称不能为空或空字符串";
          } else if (val.trim().length > 25) {
            return "名称长度限制1-25字符";
          } else {
            return true;
          }
        }
      })
        .then(({ value }) => {
          var data = {};
          data["name"] = value;
          data["parentId"] = "0"; //this.$store.state.project.flowData.rightContentTargetItem.id;
          this.$.ajax({
            url: that.httpServer + "/api/project/cat",
            method: "post",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(data),
            beforeSend: function(xhr) {
              xhr.setRequestHeader("accessToken", localStorage.accessToken);
            },
            success: function(data) {
              if (data.status == "SUCCESS") {
                that.$notify({
                  title: "成功",
                  message: data.message,
                  type: "success"
                });
                //获取添加子目录
                that.$store.dispatch("getMenuProjectList", 3);
                // that.$emit('refreshList','42349802398')
              } else if (data.status == "FAIL") {
                that.$notify.error({
                  title: "失败",
                  message: data.message
                });
              }
            },
            error: function(response) {
              that.$store.commit("dealRequestError", response);
            }
          });
        })
        .catch(() => {});
    },

    deepCopy: function(source) {
      var result;
      source instanceof Array
        ? (result = [])
        : typeof source === "object"
          ? source === null
            ? (result = "")
            : (result = {})
          : (result = source);
      for (var key in source) {
        result[key] =
          typeof source[key] === "object"
            ? this.deepCopy(source[key])
            : source[key];
      }
      return result;
    },
    localStorageSave(bool) {
      var curProjectItem = this.flowData.currentProjectDetail;
      if (curProjectItem.id) {
        var json = {
          accessToken: localStorage.accessToken,
          projectId: curProjectItem.id,
          content: this.dealFlowJson()
        };
        localStorage.setItem(
          this.username + "_" + curProjectItem.id,
          JSON.stringify(json)
        );
        console.log("localStorage save ok..." + curProjectItem.id);
      }
      if (bool) {
        //提交流程到服务端
        this.$store.dispatch("sendLocalStorageToServer", {
          projectId: curProjectItem.id
        });
      }
    },
    dealFlowJson: function() {
      var data = {};
      var nodes = this.flowData.nodes;
      var links = this.flowData.links;
      data["style"] = this.flowData.contentStyle;
      data["nodes"] = nodes;
      data["links"] = links;
      return JSON.stringify(data);
    }
  }
};
</script>
